package com.xyoto.takeawayBusiness.utils.handler;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;

/**
 * 时间拦截器.
 */

@Intercepts({@Signature(
        type = org.apache.ibatis.executor.Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class})})

public class MyBatisHandle implements Interceptor {

    @Override
    public Object intercept(Invocation invocation)
            throws Throwable
    {

        MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];

        // 获取 SQL
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        // 获取参数
        Object parameter = invocation.getArgs()[1];

        // 获取私有成员变量
        Field[] declaredFields = parameter.getClass().getSuperclass().getDeclaredFields();
//        Field[] declaredFieldsChild = parameter.getClass().getDeclaredFields();
//        ArrayList<Field> fields = new ArrayList<>(Arrays.asList(declaredFields));
//        fields.addAll(Arrays.asList(declaredFieldsChild));
//        Object[] objects = fields.toArray();
        for (Field field : declaredFields)
        {
//            Field field = (Field) object;
            if (field.getAnnotation(CreateTime.class) != null)
            {
                if (SqlCommandType.INSERT.equals(sqlCommandType))
                {
                    // insert语句插入createTime
                    field.setAccessible(true);
                    // 这里设置时间，当然时间格式可以自定。比如转成String类型
                    field.set(parameter, new Date());
                }
            }
            else if (field.getAnnotation(ModifiedTime.class) != null)
            {

                if ( SqlCommandType.UPDATE.equals(sqlCommandType))
                {
                    // insert或update语句插入updateTime
                    field.setAccessible(true);
                    field.set(parameter, new Date());
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target)
    {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties)
    {}
}
